_realname=libp11
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=0.4.12.r103.g214b271
pkgrel=1
pkgdesc="A library implementing a small layer on top of the PKCS11 API (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/OpenSC/libp11"
license=('COPYING')
makedepends=("${MINGW_PACKAGE_PREFIX}-openssl"
             "${MINGW_PACKAGE_PREFIX}-autotools"
             "${MINGW_PACKAGE_PREFIX}-cc"
             'git')
depends=("${MINGW_PACKAGE_PREFIX}-openssl")
# optdepends("${MINGW_PACKAGE_PREFIX}-p11-kit: seamless PKCS#11 modules integration")
_commit='214b271cdd066b40ad08e15ec3c19581c8dcd149'
source=("${_realname}"::"git+https://github.com/OpenSC/libp11.git#commit=${_commit}"
        0001-relocate-pkgconfig-install-paths.patch
        "engine_h_win32.patch" "verinfo.patch" "readme.msys2")
sha256sums=('d563f146009ffa22ecba600dafdfdb309f228a102ec276b31c2786eb53adc7e7'
            '2637e24bd085de10d1330a7df71ffa1d4d25265d55ce38f03788a8b641c614cc'
            '7e4a81e44543db66121ec3bd184f6677c961939a20911cc5d25018e38e56dc06'
            '73e9cf87aedf418e34a7dd41e221aaacbbf505d80a89dc7b36028a32b605f415'
            '73d7e42d25a6f109f089066e6e6c483471ab7b4f78e3401f9d3783a2fd151667')

pkgver() {
  cd "${_realname}"

  git describe --long "${_commit}" | sed 's/libp11-//g;s/\([^-]*-g\)/r\1/;s/-/./g;s/^v//g'
}

prepare() {
  cd "${_realname}"
  patch -p1 -i "${srcdir}"/engine_h_win32.patch
  patch -p1 -i "${srcdir}"/verinfo.patch
  patch -p1 -i "${srcdir}"/0001-relocate-pkgconfig-install-paths.patch

  autoreconf -fi
}

build() {
  mkdir -p "build-${MSYSTEM}" && cd "build-${MSYSTEM}"

  MSYS2_ARG_CONV_EXCL="--define-variable=prefix=" \
  ../${_realname}/configure \
    --prefix="${MINGW_PREFIX}" \
    --build="${MINGW_CHOST}" \
    --host="${MINGW_CHOST}" \
    --target="${MINGW_CHOST}" \
    --with-pkcs11-module=libp11-kit-0.dll # p11-kit lib/proxy module

  # re with-pkcs11-module: pkg-config returns an absolute path, but we want
  # things to be relocatable so hardcode the .dll name here

  make
}

package() {
  cd "build-${MSYSTEM}"

  make install DESTDIR="${pkgdir}"

  install -Dm644 "${srcdir}/${_realname}/COPYING" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
  install -Dm644 "${srcdir}/readme.msys2" "${pkgdir}${MINGW_PREFIX}/share/doc/${_realname}/readme.msys2"
}
